<?php
  /*18655166379
  18365121431 123456 需求者
  18655166379 123456 中介服务商
  18300001111 123456 个人服务商
  15056990000 fptest003 企业服务商
  30 10 15 12 4*/
  /*$asdasd = new TransferAllocationModel();
        $array = array('allocation'=>array('transfer_type'=>1,'user_role'=>2,'first_level'=>21,'second_level'=>79,'third_level'=>407,'uid'=>0,'name'=>"凄凄切切",'province_id'=>100,'city_id'=>0,'expiration_date'=>1,'mobile'=>18655458980,'status'=>0,'create_time'=>time()));
        $a_id = $asdasd->addAllocation($array);
        if($a_id){
            $array = array('config'=>array('a_id'=>$a_id,'pic'=>"asdasdasdadad.jpg",'finance'=>1,'law'=>1,'sanction'=>1,'project'=>1,'affiliate'=>1,'license'=>1,'is_sell'=>1,'brokerage_services'=>1,'transfer_agency'=>"按时请问群翁",'content'=>"戚薇戚薇戚薇戚薇"));
            $asdasd->addConfig($array);
            $array = array('ditional'=>array(array('first_level'=>16,'second_level'=>32,'expiration_date'=>2),array('first_level'=>16,'second_level'=>403,'expiration_date'=>5)));
            $asdasd->additional($a_id,$array,1);
        }
        exit;*/
  /*Redis Rpush 命令将一个或多个值插入到列表头部。 如果 key 不存在，一个空列表会被创建并执行 LPUSH 操作。 当 key 存在但不是列表类型时，返回一个错误。*/
  $redis->RPUSH('redis_queue_mess', array());
  /*Redis Lrange 返回列表中指定区间内的元素，区间以偏移量 START 和 END 指定。 其中 0 表示列表的第一个元素， 1 表示列表的第二个元素，以此类推。 你也可以使用负数下标，以 -1 表示列表的最后一个元素， -2 表示列表的倒数第二个元素，以此类推。*/
  $redis->LRANGE('redis_queue_mess', 0, 20);
  /*Redis Ltrim 对一个列表进行修剪(trim)，就是说，让列表只保留指定区间内的元素，不在指定区间之内的元素都将被删除。
  下标 0 表示列表的第一个元素，以 1 表示列表的第二个元素，以此类推。 你也可以使用负数下标，以 -1 表示列表的最后一个元素， -2 表示列表的倒数第二个元素，以此类推。*/
  $redis->LTRIM('redis_queue_mess', 21, -1);

  /**
   * 获取微信openid
   * 在homebase文件中获取，这样其他文件在继承时就直接获取可以获取到openid。
   * 通过https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect获取code，在获取code后
   * 获取openid为了避免重复请求微信提供的openid接口，需要在获取之后保存在session中。
   */

  /*省市 用户ID 手机号 创建时间 状态
  htmlspecialchars_decode($info.content)把一些预定义的 HTML 实体转换为字符
  style="-webkit-user-select: none;user-select: none;"防止文本被复制的方法之一
  一维数组重复数据过滤：
  $str = array();
  foreach ($news_label as $key => $value) {
      $str[] = str_replace(PHP_EOL, '', $value); 
      //PHP_EOL是一个些已经定义好的变量，代表php的换行符，这个变量会根据平台而变
  }
  $str = array_unique($str);//array_unique()删除数组中重复的元素，并返回值*/

  /*我就想问问这穿脚上怎么跟木头一样硬，两只脚全磨破了。*/
  /*SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 100 AND `city_id` = '' AND `first_level` = 20  AND `second_level` = 0 AND `third_level` = 0 AND `create_time` > 1509433730 AND `status` = 1 AND `uid` <> '3252'   AND `item_type` = 3  
  UNION ALL 
  SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 560 AND `city_id` = '561' AND `first_level` = 16   AND `second_level` = 17 AND `third_level` = 18 AND `create_time` > 1509433730 AND `status` = 1 AND `uid` <> '3252'  AND `item_type` = 4  
  UNION ALL 
  SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 440 AND `city_id` = '441' AND `first_level` = 20   AND `second_level` = 0 AND `third_level` = 0 AND `create_time` > 1509433730 AND `status` = 1 AND `uid` <> '3252'  AND `item_type` = 3  
  UNION ALL 
  SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 560 AND `city_id` = '564' AND `first_level` = 20   AND `second_level` = 0 AND `third_level` = 0 AND `create_time` > 1509433730 AND `status` = 1 AND `uid` <> '3252'  AND `item_type` = 3  
  UNION ALL 
  SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 100 AND `city_id` = '' AND `first_level` = 22  AND `second_level` = 233 AND `third_level` = 414 AND `create_time` > 1509433730 AND `status` = 1 AND `uid` <>  '3252' AND `item_type` = 4  
  UNION ALL 
  SELECT count(*) as count FROM zzb_aptitude a INNER JOIN zzb_rent b ON a.id = b.ap_id  WHERE a.province_id = '100'   AND a.city_id = '' AND a.first_level = '20' AND a.second_level = '0' AND a.third_level = '0' AND a.create_time >  1509433730 AND a.status = 1 AND a.uid <> '3252' AND a.item_type = 5 AND b.is_gency = '0' AND b.money_type IN   ('0','1')  UNION ALL SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 200 AND `city_id` = '' AND  `first_level` = 20 AND `second_level` = 0 AND `third_level` = 0 AND `create_time` > 1509433730 AND `status` = 1 AND  `uid` <> '3252' AND `item_type` = 3 "*/

  /*SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 100 AND `city_id` = '' AND `first_level` = 20  AND `second_level` = 0 AND `third_level` = 0 AND `create_time` > 0 AND `status` = 1 AND `uid` <> '3252' AND  `item_type` = 3 UNION ALL SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 560 AND `city_id` =   '561' AND `first_level` = 16 AND `second_level` = 17 AND `third_level` = 18 AND `create_time` > 0 AND `status` = 1  AND `uid` <> '3252' AND `item_type` = 4  UNION ALL SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id`  = 440 AND `city_id` = '441' AND `first_level` = 20 AND `second_level` = 0 AND `third_level` = 0 AND `create_time` >  0 AND `status` = 1 AND `uid` <> '3252' AND `item_type` = 3  UNION ALL SELECT count(*) as count FROM `zzb_aptitude`   WHERE `province_id` = 560 AND `city_id` = '564' AND `first_level` = 20 AND `second_level` = 0 AND `third_level` = 0   AND `create_time` > 0 AND `status` = 1 AND `uid` <> '3252' AND `item_type` = 3  UNION ALL SELECT count(*) as count  FROM `zzb_aptitude` WHERE `province_id` = 100 AND `city_id` = '' AND `first_level` = 22 AND `second_level` = 233   AND `third_level` = 414 AND `create_time` > 0 AND `status` = 1 AND `uid` <> '3252' AND `item_type` = 4
  
  select sum(count) as count from (SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 100 AND   `city_id` = '' AND `first_level` = 20 AND `second_level` = 0 AND `third_level` = 0 AND `create_time` > 1509434109   AND `status` = 1 AND `uid` <> '3252' AND `item_type` = 3  UNION ALL SELECT count(*) as count FROM `zzb_aptitude`  WHERE `province_id` = 560 AND `city_id` = '561' AND `first_level` = 16 AND `second_level` = 17 AND `third_level` =   18 AND `create_time` > 1509434109 AND `status` = 1 AND `uid` <> '3252' AND `item_type` = 4  UNION ALL SELECT  count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 440 AND `city_id` = '441' AND `first_level` = 20 AND   `second_level` = 0 AND `third_level` = 0 AND `create_time` > 1509434109 AND `status` = 1 AND `uid` <> '3252' AND  `item_type` = 3  UNION ALL SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 560 AND `city_id` =  '564' AND `first_level` = 20 AND `second_level` = 0 AND `third_level` = 0 AND `create_time` > 1509434109 AND   `status` = 1 AND `uid` <> '3252' AND `item_type` = 3  UNION ALL SELECT count(*) as count FROM `zzb_aptitude` WHERE  `province_id` = 100 AND `city_id` = '' AND `first_level` = 22 AND `second_level` = 233 AND `third_level` = 414 AND   `create_time` > 1509434109 AND `status` = 1 AND `uid` <> '3252' AND `item_type` = 4  UNION ALL SELECT count(*) as   count FROM zzb_aptitude a INNER JOIN zzb_rent b ON a.id = b.ap_id  WHERE a.province_id = '100' AND a.city_id = ''   AND a.first_level = '20' AND a.second_level = '0' AND a.third_level = '0' AND a.create_time > 1509434109 AND a. status = 1 AND a.uid <> '3252' AND a.item_type = 5 AND b.is_gency = '0' AND b.money_type IN ('0','1')  UNION ALL   SELECT count(*) as count FROM `zzb_aptitude` WHERE `province_id` = 200 AND `city_id` = '' AND `first_level` = 20  AND `second_level` = 0 AND `third_level` = 0 AND `create_time` > 1509434109 AND `status` = 1 AND `uid` <> '3252'   AND `item_type` = 3 ) as tab limit 1"
        ["advs"] => string(187) "SELECT `advspic`,`link` FROM `zzb_advs` WHERE `status` = 1 AND `position` = 4 AND  `province_id` = 0 AND `end_time` > 1512026109 AND `start_time` < 1512026109 ORDER BY level desc LIMIT 3  "
        ["intelligence"] => string(103) "SELECT COUNT(*) AS tp_count FROM `zzb_intelligence` WHERE `uid` = 3252 AND   `week` = '2017-48' LIMIT 1*/
  

  /* 省区市区排序 */
  function headerArea(){
      global $db;
      $where = "";
      $area  = array();
      $data = $db -> row_select("area", $where, "*", 0, "parentid, id asc");
      foreach($data as $key => $val){
        if($val['parentid'] == -1){
          $area[$val['id']] = $val;
          $area[$val['id']]['city'] = array();
        }else{
          if($area[$val['parentid']]){
            array_push($area[$val['parentid']]['city'], $val);
          }
        }
      }
      $areakey = array('A' => array(), 'B' => array(), 'C' => array(), 'D' => array(), 'E' => array(), 'F' => array() , 'G' => array(), 'H' => array(), 'I' => array(), 'J' => array(), 'K' => array(), 'L' => array(), 'M' => array (), 'N' => array(), 'O' => array(), 'P' => array(), 'Q' => array(), 'R' => array(), 'S' => array(), 'T' =>   array(), 'U' => array(), 'V' => array(), 'W' => array(), 'X' => array(), 'Y' => array(), 'Z' => array());
      foreach($area as $key => $val){
        array_push($areakey[$val['mark']], $val);
      }
      return $areakey;
    
      //省市区排序查询
      $re = M('area')->where('upid=0')->select();
      foreach($re as $key => $val){
          $re[$val['id']] = $val;
          $re[$val['id']]['city'] = M('area')->where('upid='.$val['id'])->select();
      }
  }

  // 1.create方法可以对POST提交的数据进行处理（通过表中的字段名称与表单提交的名称对应关系自动封装数据实例），例如user  表中有一个字段名叫"username",如果表单中有一个<input name="username" value="小明">,那么$User = M('User'); $data = $ User->create(); echo $data['username'];就会输出"小明",不用你用$_POST['username']去接收。
  // 2.用create方法可以对表单进行令牌验证,防止表单重复提交。
  $kucun = M('kucun');
  $kucun->create();
  $kucun->ctime=time();
  $kucun->add();
  $this->redirect('cangku');


  //函数以其他字符替换字符串中的一些字符（区分大小写）。
  str_replace();

  /*submit快捷键：
  Ctrl+Shift+D选中复制 Ctrl+Shift+V格式化粘贴 Ctrl+Shift+M选中某个括号内的所以函数  Ctrl+Shift+Alt+↑ 数字加10   Ctrl+↑数字加1 Ctrl+M跳对应括号  Ctrl+D选中相同
  
  Ctrl+R函数定位  Ctrl+G行定位  Ctrl+[]左右缩进  Ctrl+J列变行  Ctrl+enter下一行  Ctrl+Shift+enter上一行  Ctrl+Shift+a   html中选中标签之间内容
  
  Ctrl+Shift+右键 竖行选择  Ctrl+k+l转小写   Ctrl+k+u转大写  Ctrl+Y前进   Ctrl+
  
  Alt+Shift+W 选中标签里内容 Ctrl+Shift+; 删除标签  Ctrl+Shift+''(单引号)  选中标签*/

  $_SERVER['SERVER_ADDR'];
  $_SERVER['REMOTE_ADDR'];
  $_SERVER['REMOTE_PORT'];
  echo "服务器IP地址".$_SERVER['SERVER_ADDR'];
  echo "用户IP地址".$_SERVER['REMOTE_ADDR'];
  echo "用户端口".$_SERVER['REMOTE_PORT'];

  public function add()
  {
    if (IS_POST) {
    //把前台input标签中存放的一维数组转换成二位数组
     foreach ($_POST['asd'] as $key => $value){
      // explode()把字符串切成数组。implode（）把数组切成字符串。
       $a[] = array('aid'=>explode(',',$value)[1],'uid'=>explode(',',$value)[0],'status'=>1,'create_time'=>NOW_TIME);
           }  
        $result = M('core_attendance_detail')->addAll($a);//addALL()数据批量增加到数据库中
      if($result){
        $this->success('添加成功',U('index'));
      }else{
        $this->error('添加失败');
      }
    }
  }

  // Thinkphp 中 在控制器里关于前置和后置的方法
  public function _before_index()
  {
    //手动设置编码格式
    header('content-type:text/html;charset=utf-8');
  }
  /*
  可以使用的修饰符包括：
  修饰符 作用
  S 强制转换为字符串类型
  d 强制转换为整形类型
  b 强制转换为布尔类型
  a 强制转换为数组类型
  f 强制转换为浮点类型*/

  //多表关联查询
  select * form hd_user u left join hd_role_user ru on u.id = ru.user_id left join hd_role r on ru.role_id = r.id;
  /*创建视图表，只能用来查询
  create view dksp_core_recommend_view as
  select 
  t.*,
  u.title 
  from dksp_core_recommend t
    left join dksp_core_unit u on u.id = t.unit;
  
  //创建多表关联的视图表
  create view 表名 as select t.*,
  u.字段名 as 新字段名,
  x.字段名 as 新字段名,
  y.字段名 as 新字段名,
  z.字段名 as 新字段名
  
  from 表名 t 
  left join 关联表名 u on u.id = t.uid 
  left join 关联表名 x on x.id = t.xid 
  left join 关联表名 y on y.id = t.yid 
  left join 关联表名 z on z.id = t.zid*/ 


  Thinkphp按时间范围查询:
  array(between,array(strtotime(I('create_time')),strtotime(I('create_time').'23:59:58')));

  public function FunctionName(
  {
    //手机号码归属地完整代码参考资料
    //设置编码格式  
    header('Content-type:text/html;charset=utf-8');

    //定义手机号码查询接口的地址
    $apiurl = 'http://apis.juhe.cn/mobile/get'; 

    //将申请的手机号码归属地查询接口的appkey
    $params = array(
      'key' => 'b4b88a8ffc09e2fd3f24251ee19fa168', 
      'phone' => '18626088426' //要查询的手机号码
    );

    //返回一个 URL 编码后的字符串。
    $paramsString = http_build_query($params);

    //把变量变成字符串读取
    $content = @file_get_contents($apiurl.'?'.$paramsString);

    //进行json编码格式编译
    $result = json_decode($content,true);

    //print_r($result);exit;
    if($result['error_code'] == '0'){
        if($result['result']['areacode'] == 0533){
            echo "省份：".$result['result']['province']."\r\n";
            echo "城市：".$result['result']['city']."\r\n";
            echo "区号：".$result['result']['areacode']."\r\n";
            echo "邮编：".$result['result']['zip']."\r\n";
            echo "运营商：".$result['result']['company']."\r\n";
            echo "类型：".$result['result']['card']."\r\n";
        }else{
            echo "对不起，此活动仅限于淄博地址手机用户参加";
        }
        /*
        "province":"浙江",
        "city":"杭州",
        "areacode":"0571",
        "zip":"310000",
        "company":"中国移动",
        "card":"移动动感地带卡"
        */
        
    }else{
        echo $result['reason']."(".$result['error_code'].")";
    }
  }

  /*模糊查询
  $map['title'] = array('like', '%' . $keyword . '%');
  friendlyDate：自带函数格式化时间，显示友好时间，如：5分钟前，3天前等
  {$vo.create_time|friendlyDate}
  富文本字符串截取
  {$vo.detail|htmlspecialchars_decode|strip_tags|substr=###,0,400}
  htmlspecialchars_decode：html代码格式化
  strip_tags：只留文本字符函数
  substr：截取数量从0到400
  //事物：开启需要事物的表，表的操作属性的储存类型必须为InnoDB
  D('core_unit_config')->startTrans();
  D('core_unit')->startTrans();
  if(IS_POST){
      $result  = M('core_unit_config')->where('unit = '.I('uid'))->select();
      //dump($result);exit;
      if(!$result){
          $data['model'] = I('model');
          $data['attendance_model'] = I('attendance_model');
          $data['attendance_days'] = I('attendance_days');
          //$data['create_time'] = time();
          $data['unit'] = I('uid');
          $res = M('core_unit')->where('id ='.I('uid'))->save($data);
          $res1 = M('core_unit_config')->add($data);
      }else{
          $data['model'] = I('model');
          $data['attendance_model'] = I('attendance_model');
          $data['attendance_days'] = I('attendance_days');
          $data['update_time'] = time();
          $res = M('core_unit')->where('id ='.I('uid'))->save($data);
          $res1 = M('core_unit_config')->where('unit ='.I('uid'))->save($data);
      }

      //如果为真就执行事物的提交，添加数据
      if($res&&$res1){
          M('core_unit_config')->commit();
          M('core_unit')->commit();
          $this->redirect('IndexPC/unitconf');
      }
      else{
          M('core_unit_config')->rollback();
          M('core_unit')->rollback();
          $this->error('更新失败');
      }
  }*/

  /*thinkphp框架自带的加密方法
  function think_ucenter_md5($str, $key = 'ThinkUCenter'){
          return '' === $str ? '' : md5(sha1($str) . $key);
      }
  md5(sha1("admin") . ';H8%Vizh-wBcu|"F}?$t~!=@30bOn`G#&ZP(/7Qg');
  在Application/User/Conf/config.php文件中*/

  //当天时间
  $where['time'] = array(
      array('egt',strtotime(date('Y-m-d',time())),
      array('lt',strtotime(date('Y-m-d',time())).'+1 day')
  );
  // 本周时间
  $where['time'] = array(
      array('egt',strtotime(date('Y-m-d',time())).'-'.date('w',time()).' day'),
      array('lt',strtotime(date('Y-m-d',time())).'+1 week -'.date('w',time()).' day'); 
  );
  // 本月时间
  $where['time'] = array(
      array('egt',strtotime(date('Y-m',time()))),
      array('lt',strtotime(date('Y-m',time()).'+1 month'))
  );
  // 本年时间
  $where['time'] = array(
      array('egt',strtotime(date('Y',time()))),
      array('lt',strtotime(date('Y',time()).'+1 year'))
  );

  //上传图片
  public function addModular(){
      //设置编码格式
      header('content-type:text/html;charset=utf-8');
      if(IS_POST)
      {
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize  = 3145728 ;// 设置附件上传大小
        $upload->allowExts  = array('png','jpg','txt');// 设置附件上传类型
        $upload->savePath =  './Uploads/Picture/'.date('Ymd').'/';// 设置附件上传目录
        if(!$upload->upload()) {// 上传错误提示错误信息
            $this->error($upload->getErrorMsg());
        }else{// 上传成功 获取上传文件信息
            $info =  $upload->getUploadFileInfo();
        }
          $data['title'] = trim(I('post.title'));
          $data['image'] = $info[0]['savepath'].$info[0]['savename'];
          $data['ctime'] = time();
          if(M('core_station_modular')->add($data)){
              $this->success("新增成功",U('Modular'));             
          }else{
              $this->errot("新增失败");
          }
      }else{
        $this->meta_title = '新增岗位模块';
        $this->display(self::MODEL_NAME . 'Station/addModular');
      }
    }
  //流水导出
  // public function bill_export(){
  //   header('Content-type:text/html;charset=utf8');
  //   import("Org.Util.PHPExcel");
  //   $data = M('shangpin')->select();
  //   $resultPHPExcel = new \PHPExcel(); //一定要加跟杠，不然报错
  //   $resultPHPExcel->getActiveSheet()->setCellValue('A1', '姓名');
  //   $resultPHPExcel->getActiveSheet()->setCellValue('B1', '班级');
  //   $resultPHPExcel->getActiveSheet()->setCellValue('C1', '缴费项');
  //   $resultPHPExcel->getActiveSheet()->setCellValue('D1', '总金额');
  //   $resultPHPExcel->getActiveSheet()->setCellValue('E1', '明细');
  //   $resultPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
  //   $resultPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
  //   $resultPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
  //   $resultPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
  //   $resultPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
  //   $i = 2;
  //   foreach ($data as $item) {
  //       $resultPHPExcel->getActiveSheet()->setCellValue('A' . $i, $item['uid']);
  //       $resultPHPExcel->getActiveSheet()->setCellValue('B' . $i, $item['username']);
  //       $resultPHPExcel->getActiveSheet()->setCellValue('C' . $i, $item['shangpinname']);
  //       $resultPHPExcel->getActiveSheet()->setCellValue('D' . $i, $item['lujing']);
  //       $resultPHPExcel->getActiveSheet()->setCellValue('E' . $i,$item['ctime']);
  //       $i++;
  //   }
  //   //设置导出文件名
  //   $outputFileName = 'bills.xls';
  //   $xlsWriter      = new \PHPExcel_Writer_Excel5($resultPHPExcel);
  //   header("Content-Type: application/force-download");
  //   header("Content-Type: application/octet-stream");
  //   header("Content-Type: application/download");
  //   header('Content-Disposition:inline;filename="' . $outputFileName . '"');
  //   header("Content-Transfer-Encoding: binary");
  //   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  //   header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  //   header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  //   header("Pragma: no-cache");
  //   $xlsWriter->save("php://output");
  // }

  /*获取当前方法名
  dump(__CONTROLLER__ );
  dump(ACTION_NAME);
  dump(CONTROLLER_NAME);
  dump(__ACTION__);exit;

  限制字数格式(false:是否显示省略号)
  {$v.intro|msubstr=###,0,2,'utf-8',false}*/

  //构造函数必须先继承父类的构造函数 
  public function __construct()
  {
      header('content-type:text/html;charset=utf-8');
      //继承父类构造函数
      parent::__construct();
      $result = M('member')->where('uid = 110')->find();
      $this->_SESSION['uid'] = $result['uid'];
      $this->_SESSION['nickname'] = $result['nickname'];
      $this->_SESSION['openid']   = $result['openid'];
      $this->_SESSION['depart_id'] = $result['depart_id'];
      $this->_SESSION['station_id'] = $result['station_id'];
  }

  //通讯录
 public function getFirstChar($s){
    $s0 = mb_substr($s,0,3);                 //获取名字的姓 
    $s = iconv('UTF-8','gb2312', $s0);       //将UTF-8转换成GB2312编码  
    //dump($s0);
    if (ord($s0)>128) {                      //汉字开头，汉字没有以U、V开头的  
        $asc=ord($s{0})*256+ord($s{1})-65536;  
        if($asc>=-20319 and $asc<=-20284)return "A";  
        if($asc>=-20283 and $asc<=-19776)return "B";  
        if($asc>=-19775 and $asc<=-19219)return "C";  
        if($asc>=-19218 and $asc<=-18711)return "D";  
        if($asc>=-18710 and $asc<=-18527)return "E";  
        if($asc>=-18526 and $asc<=-18240)return "F";  
        if($asc>=-18239 and $asc<=-17760)return "G";  
        if($asc>=-17759 and $asc<=-17248)return "H";  
        if($asc>=-17247 and $asc<=-17418)return "I";              
        if($asc>=-17417 and $asc<=-16475)return "J";               
        if($asc>=-16474 and $asc<=-16213)return "K";               
        if($asc>=-16212 and $asc<=-15641)return "L";               
        if($asc>=-15640 and $asc<=-15166)return "M";               
        if($asc>=-15165 and $asc<=-14923)return "N";               
        if($asc>=-14922 and $asc<=-14915)return "O";               
        if($asc>=-14914 and $asc<=-14631)return "P";               
        if($asc>=-14630 and $asc<=-14150)return "Q";               
        if($asc>=-14149 and $asc<=-14091)return "R";               
        if($asc>=-14090 and $asc<=-13319)return "S";               
        if($asc>=-13318 and $asc<=-12839)return "T";               
        if($asc>=-12838 and $asc<=-12557)return "W";               
        if($asc>=-12556 and $asc<=-11848)return "X";               
        if($asc>=-11847 and $asc<=-11056)return "Y";               
        if($asc>=-11055 and $asc<=-10247)return "Z";   
    }else if(ord($s)>=48 and ord($s)<=57){ //数字开头  
        switch(iconv_substr($s,0,1,'utf-8')){  
            case 1:return "Y";  
            case 2:return "E";  
            case 3:return "S";  
            case 4:return "S";  
            case 5:return "W";  
            case 6:return "L";  
            case 7:return "Q";  
            case 8:return "B";  
            case 9:return "J";  
            case 0:return "L";  
        }                 
    }else if(ord($s)>=65 and ord($s)<=90){ //大写英文开头  
        return substr($s,0,1);  
    }else if(ord($s)>=97 and ord($s)<=122){ //小写英文开头  
        return strtoupper(substr($s,0,1));  
    }  
    else  
    {  
        return iconv_substr($s0,0,1,'utf-8');  
        //中英混合的词语，不适合上面的各种情况，因此直接提取首个字符即可  
    }  
  } 

  public function addPeople(){
    $userName = array('张三','李四','王五','小二','猫蛋','狗蛋','王花','三毛','小明','李刚','张飞');  
    sort($userName);  
    foreach($userName as $name){ 
        $char = $this->getFirstChar($name);  
        $nameArray = array(); 
        if(count($charArray[$char])!=0){  
           $nameArray = $charArray[$char];  
        }  
        array_push($nameArray,$name);   
        $charArray[$char] = $nameArray;
    }  
    ksort($charArray);
    $this->assign('_list',$charArray);
    $this->display();
  }

  /*控制数组指针位置：current()、key()、next()、prey()、end()、reset()
  current():取得目前指针位置的内容资料。
  key():读取目前指针所指向资料的索引值（键值）。
  next():将数组中的内部指针移动到下一个单元。
  prev():将数组的内部指针倒回一位。
  end():将数组的内部指针指向最后一个元素。
  reset():将目前指针无条件移至第一个索引位置。*/

  /*$arr = array('one'=>"第一",'two'=>'第二','three'=>'第三','four'=>'第四','five'=>'第五');
  取第二方法：key(arr)取出第一，在next(arr);
  
  $contact = array(
  "ID" => 1,
  "姓名" => "高某",
  "公司" => "A公司",
  "地址" => "北京市",
  "电话" => "(010)98765432",
  "EMAIL" => "gao@brophp.com",
  );
   
  //数组刚声明时，数组指针在数组中第一个元素位置
  echo '第一个元素：'.key($contact).' => '.current($contact).'<br>'; //第一个元素
  echo '第一个元素：'.key($contact).' => '.current($contact).'<br>'; //数组指针没动
   
  next($contact);
  next($contact);
  echo '第三个元素：'.key($contact).' => '.current($contact).'<br>'; //第三个元素
   
  end($contact);
  echo '最后一个元素：'.key($contact).' => '.current($contact).'<br>';
   
  prev($contact);
  echo '倒数第二个元素：'.key($contact).' => '.current($contact).'<br>';
   
  reset($contact);
  echo '又回到了第一个元素：'.key($contact).' => '.current($contact).'<br>';*/

  //获取openid：用户信息
  public function getUserInfo(){
    //配置参数的数组
    $CONF =  array(
        '__APPID__' =>'wx454ee1bd0c3943d6',
        '__SERECT__' =>'73a010f5911b41c74b989c24772ee38f',
        '__CALL_URL__' =>'https://www.biz work.cn/index.php?s=/Home/Index/getUserInfo' //当前页地址
    );
    //没有传递code的情况下，先登录一下
    if(!isset($_GET['code']) || empty($_GET['code'])){

        $getCodeUrl  =  'https://open.weixin.qq.com/connect/oauth2/authorize'.
                        '?appid=' . $CONF['__APPID__'] .
                        '&redirect_uri=' . $CONF['__CALL_URL__']  . 
                        '&response_type=code'.
                        '&scope=snsapi_userinfo'. #!!!scope设置为snsapi_base !!!
                        '&state=123#wechat_redirect';

        //跳转微信获取code值,去登陆   
        header('Location:' . $getCodeUrl);
        exit;
    }

    $code           =   trim($_GET['code']);
    //使用code，拼凑链接获取用户openid 
    $getTokenUrl    =   'https://api.weixin.qq.com/sns/oauth2/access_token'.
                        '?appid='.$CONF['__APPID__'].
                        '&secret='.$CONF['__SERECT__'].
                        '&code='.$code.
                        '&grant_type=authorization_code';
    /**摘要： 
    在这篇文章中主要讲解php_curl库的知识，并教你如何更好的使用php_curl。 
    简介 
    你可能在你的编写PHP脚本代码中会遇到这样的问题：怎么样才能从其他站点获取内容呢？这里有几个解决方式；最简单的就是在php中使用fopen()函数，但是fopen函数没有足够的参数来使用，比如当你想构建一个“网络爬虫”，想定义爬虫的客户端描述(IE,firefox),通过不同的请求方式来获取内容，比如POST,GET；等等这些需求是不可能用fopen()函数实现的。 
    为了解决我们上面提出的问题，我们可以使用PHP的扩展库-Curl，这个扩展库通常是默认在安装包中的,你可以它来获取其他站点的内容，也可以来干别的。 
    备注：这两段代码需要php_curl扩展库的支持，查看phpinfo()，如果curl support　enabled则表示支持curl库。*/ 

    // 通过函数curl_init()创建一个新的curl会话
    $ch = curl_init();
    // 传递一个URL给curl_setopt()函数
    curl_setopt($ch,CURLOPT_URL,$getTokenUrl);
    curl_setopt($ch,CURLOPT_HEADER,0);
    // 在curl_setopt()函数的参数中，如果希望获得内容但不输出,使用 CURLOPT_RETURNTRANSFER参数,并设为非0值/true!
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    //curl将会获取URL站点的内容，并打印出来。
    $res = curl_exec($ch);
    // 关闭当前的curl会话
    curl_close($ch);
    // json_decode() 函数用于对 JSON 格式的字符串进行解码，并转换为 PHP 变量
    // assoc: 当该参数为 TRUE 时，将返回数组，FALSE 时返回对象。
    $str = json_decode($res,true); //获取openid
    //根据openid 获取用户基本信息
    $getTokenUrl    =   'https://api.weixin.qq.com/sns/userinfo'.
                        '?access_token='.$str['access_token'].
                        '&openid='.$str['openid'].
                        '&lang=zh_CN';
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$getTokenUrl);
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    $str = json_decode($res,true);
  //获取客户端IP
  function getClientIP(){  
    global $ip;  
    if (getenv("HTTP_CLIENT_IP"))  
        $ip = getenv("HTTP_CLIENT_IP");  
    else if(getenv("HTTP_X_FORWARDED_FOR"))  
        $ip = getenv("HTTP_X_FORWARDED_FOR");  
    else if(getenv("REMOTE_ADDR"))  
        $ip = getenv("REMOTE_ADDR");  
    else $ip = "Unknow";  
    return $ip;  
  }  

  //微信消息推送：子函数
  public function http_request($url,$data=array()){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
  }
  //微信消息推送
  //参数：
  //openid    :用户微信openid
  //type      :消息类型，例如：任务消息；审核消息
  //title     :信息名称，例如：工作通维护；用车申请
  //send      :发布人名称
  //url       :此消息详情跳转地址，例如：https://www.bizwork.cn/index.php?s=/Task/Index/tasklist(  如需带参数，请在后面拼接上)
  public function messageWX($openid = 'oaDQet0crJHS-9iznnRFsdPx-858', $type = '任务接收', $title = '工作通维护',$send  = '测试',$url = 'https://www.bizwork.cn/index.php?s=/Task/Index/tasklist')
  {
    header("Content-type:text/html;charset=utf-8");
    $appid  = 'wx454ee1bd0c3943d6';
    $secret = '73a010f5911b41c74b989c24772ee38f';
    $json_token=$this->http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret);
    $access_token=json_decode($json_token,true);
     //获得access_token
    $acc=$access_token['access_token'];
     // echo $this->access_token;exit;
     //模板消息
    $template=array(
            'touser'=>$openid,
            'template_id'=>"vtkgAYHwQedH0YbAMurT48oAX86TqQa4PocsvgDl2Es",
            'url'=>$url,
            'topcolor'=>"#7B68EE",
            'data'=>array(
                    'first'=>array('value'=>urlencode($type),'color'=>"#FF0000"),
                    'keyword1'=>array('value'=>urlencode($title),'color'=>'#0066FF'),
                    'keyword2'=>array('value'=>urlencode($send),'color'=>'#0066FF')
                )
                );
    $json_template=json_encode($template);
     //echo $json_template;
     //echo $this->access_token;
    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$acc;
    $res=$this->http_request($url,urldecode($json_template));
    if (!($res['errcode']==0)){
        echo '发送失败';
    }
  }
?>